package com.party.mobile.web.controller.partner;

import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.partner.PartnerLabel;
import com.party.core.model.partner.PartnerMemberLabel;
import com.party.core.model.partner.PartnerRealUserOutput;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.partner.IPartnerLabelService;
import com.party.core.service.partner.IPartnerMemberLabelService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员管理控制层
 * party
 * Created by huaqunhao
 * on 2018/8/22 0024.
 */
@Controller
@RequestMapping(value = "/partner/membermanagement")
public class MemberManagementController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IPartnerLabelService partnerLabelService;
    @Autowired
    private IPartnerMemberLabelService partnerMemberLabelService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 移动到会员
     *
     * @param userIds 用户
     * @return 交互数据!
     */
    @Transactional
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/moveToMember")
    public AjaxResult moveToMember(Integer transferType, String userIds, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        //数据验证
        if ((userIds == null || userIds.length() == 0) || transferType == null) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
        }
        try {
            String[] udarrs = userIds.split(",");
            //0:用户->会员
            if (0 == transferType) {
                for (String id : udarrs) {

                    PartnerMemberLabel pmlObj = partnerMemberLabelService.getMemberLabel(currentUser.getId(), id);
                    if (null == pmlObj) {
                        //用户之前没有添加过标签
                        PartnerMemberLabel partnerMemberLabel = new PartnerMemberLabel();
                        partnerMemberLabel.setOrganizationId(currentUser.getId());
                        partnerMemberLabel.setMemberId(id);
                        partnerMemberLabel.setIsMember(PartnerLabel.REAL_MEMBER);
                        partnerMemberLabelService.insert(partnerMemberLabel);
                    } else {
                        String labName = "";

                        if (StringUtils.isNotBlank(pmlObj.getLabelId())) {
                            PartnerLabel plobj = partnerLabelService.get(pmlObj.getLabelId());

                            plobj.setType(PartnerLabel.REAL_MEMBER);

                            labName = plobj.getLabelName();
                            List<PartnerLabel> plObj_2 = partnerLabelService.findByPartnerLabel(plobj);
                            if (plObj_2.size() > 0) {
                                //且标签名跟会员的相同
                                pmlObj.setLabelId(plObj_2.get(0).getId());

                                pmlObj.setIsMember(PartnerLabel.REAL_MEMBER);
                                partnerMemberLabelService.update(pmlObj);
                            }
                        }

                        if (StringUtils.isNotBlank(labName)) {
                            //标签名唯一的
                            PartnerLabel plObj_1 = new PartnerLabel();
                            plObj_1.setLabelName(labName);
                            plObj_1.setOrganizationId(currentUser.getId());
                            plObj_1.setType(PartnerLabel.REAL_MEMBER);


                            pmlObj.setLabelId(partnerLabelService.insert(plObj_1));
                        }


                        pmlObj.setIsMember(PartnerLabel.REAL_MEMBER);
                        partnerMemberLabelService.update(pmlObj);

                    }
                }
            }
            //1:会员->用户
            if (1 == transferType) {
                for (String id : udarrs) {
                    PartnerMemberLabel pmlObj = partnerMemberLabelService.getMemberLabel(currentUser.getId(), id);
                    pmlObj.setIsMember(PartnerLabel.REAL_USER);
                    pmlObj.setLabelId("");

                    partnerMemberLabelService.update(pmlObj);

                }
            }

        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success((Object) userIds);
    }

    /**
     * 移动到会员
     *
     * @param userIds 用户
     * @return 交互数据!
     */
    @Transactional
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/moveToMember/v2")
    public AjaxResult moveToMemberV2(Integer transferType, String userIds, HttpServletRequest request) {
        //数据验证
        if ((StringUtils.isEmpty(userIds)) || transferType == null) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
        }
        try {
            String[] userArray = userIds.split(",");

            for (String o : userArray) {
                String[] s = o.split("_");
                String userId = s[0];
                String partnerId = s[1];

                if (0 == transferType) {
                    // 0:用户->会员

                    PartnerMemberLabel pmlObj = partnerMemberLabelService.getMemberLabel(partnerId, userId);
                    if (null == pmlObj) {
                        //用户之前没有添加过标签
                        PartnerMemberLabel partnerMemberLabel = new PartnerMemberLabel();
                        partnerMemberLabel.setOrganizationId(partnerId);
                        partnerMemberLabel.setMemberId(userId);
                        partnerMemberLabel.setIsMember(PartnerLabel.REAL_MEMBER);
                        partnerMemberLabelService.insert(partnerMemberLabel);
                    } else {
                        String labName = "";
                        if (StringUtils.isNotBlank(pmlObj.getLabelId())) {
                            PartnerLabel partnerLabel = partnerLabelService.get(pmlObj.getLabelId());
                            partnerLabel.setType(PartnerLabel.REAL_MEMBER);
                            labName = partnerLabel.getLabelName();
                            List<PartnerLabel> plObj_2 = partnerLabelService.findByPartnerLabel(partnerLabel);
                            if (plObj_2.size() > 0) {
                                //且标签名跟会员的相同
                                pmlObj.setLabelId(plObj_2.get(0).getId());
                                pmlObj.setIsMember(PartnerLabel.REAL_MEMBER);
                                partnerMemberLabelService.update(pmlObj);
                            }
                        }

                        if (StringUtils.isNotBlank(labName)) {
                            //标签名唯一的
                            PartnerLabel partnerLabel = new PartnerLabel();
                            partnerLabel.setLabelName(labName);
                            partnerLabel.setOrganizationId(partnerId);
                            partnerLabel.setType(PartnerLabel.REAL_MEMBER);
                            pmlObj.setLabelId(partnerLabelService.insert(partnerLabel));
                        }
                        pmlObj.setIsMember(PartnerLabel.REAL_MEMBER);
                        partnerMemberLabelService.update(pmlObj);
                    }
                } else if (1 == transferType) {
                    // 1:会员->用户
                    PartnerMemberLabel pmlObj = partnerMemberLabelService.getMemberLabel(partnerId, userId);
                    if (null != pmlObj) {
                        pmlObj.setIsMember(PartnerLabel.REAL_USER);
                        pmlObj.setLabelId("");
                        partnerMemberLabelService.update(pmlObj);
                    }
                }
            }
        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success((Object) userIds);
    }

    /**
     * 获取标签列表
     *
     * @param request
     * @return 交互数据!
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/getLables")
    public AjaxResult getLables(Integer isMember, String partnerId, HttpServletRequest request) {
        List<Map<String, Object>> plmaps = new ArrayList<>();
        try {
            if (null == isMember) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
            }
            //子账号数据过滤
            List<String> orgIds = null;
            if (StringUtils.isEmpty(partnerId)) {
                CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
                orgIds = memberGroupService.getChildWithMy(currentUser.getId());
            }

            List<PartnerLabel> pllist = partnerLabelService.getLabels(partnerId, orgIds, isMember);
            for (PartnerLabel pl : pllist) {
                Map<String, Object> plmap = new HashMap<>();
                plmap.put("id", pl.getId());
                plmap.put("labelName", pl.getLabelName());
                plmap.put("labelNum", partnerMemberLabelService.getLabelNum(pl.getOrganizationId(), pl.getId()));
                plmap.put("partnerId", pl.getOrganizationId());
                plmaps.add(plmap);
            }
        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success(plmaps);
    }

    /**
     * 删除标签
     *
     * @param labId
     * @param request
     * @return 交互数据!
     */
    @Transactional
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/delLable")
    public AjaxResult delLable(String labId, HttpServletRequest request) {
        try {
            partnerLabelService.delete(labId);
            //将标签下的人的labId设置为“”
            partnerMemberLabelService.deleteLable(labId);
        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success((Object) labId);
    }

    /**
     * 编辑会员标签
     *
     * @param labId
     * @param memberId
     * @param request
     * @return 交互数据!
     */
    @Transactional
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/editMemberLable")
    public AjaxResult editMemberLable(Integer isMember, String labId, String memberId, String labelName, String partnerId, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        try {
            //labId  memberId :inset delete
            //labelName memberId  :update
            if (null == isMember) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过，isMember未传");
            }
            //机构id
            String orgId = currentUser.getId();
            if (StringUtils.isNotEmpty(partnerId)) {
                orgId = partnerId;
            }

            //为用户添加标签列表中没有的标签
            if (StringUtils.isNotBlank(labelName)) {

                PartnerLabel plObj_1 = new PartnerLabel();
                plObj_1.setLabelName(labelName);
                plObj_1.setOrganizationId(orgId);
                plObj_1.setType(isMember);
                List<PartnerLabel> plObj_2 = partnerLabelService.findByPartnerLabel(plObj_1);
                if (plObj_2.size() > 0) {
                    return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "重复标签名");
                }

                labId = partnerLabelService.insert(plObj_1);
            }

            PartnerMemberLabel pmbObj = partnerMemberLabelService.getMemberLabel(orgId, memberId);
            if (null == pmbObj) {
                PartnerMemberLabel pmbObj_c = new PartnerMemberLabel();
                pmbObj_c.setOrganizationId(orgId);
                pmbObj_c.setMemberId(memberId);
                pmbObj_c.setLabelId(labId);
                pmbObj_c.setIsMember(isMember);
                partnerMemberLabelService.insert(pmbObj_c);
            } else {

                pmbObj.setLabelId(labId);

                partnerMemberLabelService.update(pmbObj);
            }

        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success((Object) memberId);
    }

    /**
     * 获取标签详情
     *
     * @param labId
     * @param memberId
     * @param request
     * @return 交互数据!
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/getLableInfo")
    public AjaxResult getLableInfo(String memberId, String labId, String partnerId, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (StringUtils.isBlank(memberId) && StringUtils.isBlank(labId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
        }
        Map<String, Object> mmp = new HashMap<>();
        try {
            if (StringUtils.isEmpty(partnerId)) {
                partnerId = currentUser.getId();
            }
            //获取标签名
            String labelName = "";
            String labId_c = null;

            //获取用户标签详情
            List<Map<String, Object>> plmaps = new ArrayList<>();
            if (StringUtils.isNotBlank(memberId)) {

                PartnerMemberLabel pmlobj = partnerMemberLabelService.getMemberLabel(currentUser.getId(), memberId);
                if (null != pmlobj && StringUtils.isNotBlank(pmlobj.getLabelId())) {
                    labelName = partnerLabelService.get(pmlobj.getLabelId()).getLabelName();
                    labId_c = pmlobj.getLabelId();
                }
                //子账号数据过滤
                List<String> orgIds = memberGroupService.getChildWithMy(currentUser.getId());
//                List<String> orgIds = null;
                List<PartnerLabel> pllist = partnerLabelService.getLabels(currentUser.getId(), orgIds, PartnerLabel.REAL_MEMBER);
                for (PartnerLabel pl : pllist) {
                    Map<String, Object> plmap = new HashMap<>();
                    plmap.put("id", pl.getId());
                    plmap.put("labelName", pl.getLabelName());
                    plmaps.add(plmap);
                }
            }
            //获取标签详情
            List<Map<String, String>> members = new ArrayList<>();
            if (StringUtils.isNotBlank(labId)) {
                labelName = partnerLabelService.get(labId).getLabelName();
                labId_c = labId;
                members = partnerLabelService.getLabelMembers(partnerId, labId);
            }
            mmp.put("labId", labId_c);
            mmp.put("labelName", labelName);
            mmp.put("lables", plmaps);
            mmp.put("members", members);

        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success(mmp);
    }

    /**
     * 编辑标签
     *
     * @param labId
     * @param labelName
     * @param labelName
     * @param request
     * @return 交互数据!
     */
    @Transactional
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdateLable", method = RequestMethod.POST)
    public AjaxResult saveOrUpdateLable(String labId, String labelName, String addMembers, String delMembers, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (StringUtils.isBlank(labelName)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
        }
        String orgId = currentUser.getId();


        try {
            PartnerLabel plObj = partnerLabelService.get(labId);
            String labId_c = labId;
            //添加新标签
            if (plObj == null) {
                plObj = new PartnerLabel();
                plObj.setLabelName(labelName);
                plObj.setOrganizationId(orgId);
                plObj.setType(PartnerLabel.REAL_MEMBER);

                List<PartnerLabel> plObj_2 = partnerLabelService.findByPartnerLabel(plObj);
                if (plObj_2.size() > 0) {
                    return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "重复标签名");
                }
                labId_c = partnerLabelService.insert(plObj);
            }
            //编辑标签
            else {
                if (!plObj.getLabelName().equals(labelName)) {
                    plObj = new PartnerLabel();
                    plObj.setLabelName(labelName);
                    plObj.setOrganizationId(orgId);
                    plObj.setType(PartnerLabel.REAL_MEMBER);

                    List<PartnerLabel> plObj_2 = partnerLabelService.findByPartnerLabel(plObj);
                    if (plObj_2.size() > 0) {
                        return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "重复标签名");
                    }
                }
                plObj.setLabelName(labelName);
                partnerLabelService.update(plObj);
            }

            //添加会员
            if (null != addMembers && addMembers.length() != 0) {
                String[] addarrs = addMembers.split(",");
                for (String am : addarrs) {

                    PartnerMemberLabel pmbObj = partnerMemberLabelService.getMemberLabel(orgId, am);
                    if (null == pmbObj) {
                        PartnerMemberLabel pmlobj = new PartnerMemberLabel();
                        pmlobj.setOrganizationId(orgId);
                        pmlobj.setLabelId(labId_c);
                        pmlobj.setMemberId(am);
                        pmlobj.setIsMember(PartnerLabel.REAL_MEMBER);
                        partnerMemberLabelService.insert(pmlobj);
                    } else {
                        pmbObj.setIsMember(PartnerLabel.REAL_MEMBER);
                        pmbObj.setLabelId(labId_c);
                        partnerMemberLabelService.update(pmbObj);
                    }
                }
            }

            //删除会员
            if (null != delMembers && delMembers.length() > 0) {
                String[] delarrs = delMembers.split(",");
                for (String am : delarrs) {
                    PartnerMemberLabel pmlobj = partnerMemberLabelService.getMemberLabel(orgId, am);
                    pmlobj.setLabelId("");

                    partnerMemberLabelService.update(pmlobj);
                }
            }

        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success((Object) labId);
    }

    /**
     * 保存或编辑标签
     *
     * @param labId      标签id
     * @param labelName  标签名称
     * @param addMembers 添加的用户id
     * @param delMembers 删除的用户id
     * @param orgId      机构id
     * @param request
     * @return 交互数据!
     */
    @Transactional
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdateLable/v2", method = RequestMethod.POST)
    public AjaxResult saveOrUpdateLableV2(String labId, String labelName, String addMembers, String delMembers, String orgId, HttpServletRequest request) {
        if (StringUtils.isBlank(labelName)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
        }
        try {
            PartnerLabel query = new PartnerLabel();
            query.setLabelName(labelName);
            query.setOrganizationId(orgId);
            query.setId(labId);
            query.setType(PartnerLabel.REAL_MEMBER);

            List<PartnerLabel> plObj_2 = partnerLabelService.findByPartnerLabel(query);
            if (plObj_2.size() > 0) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "重复标签名");
            }


            if (StringUtils.isEmpty(labId)) {
                PartnerLabel pl = new PartnerLabel();
                pl.setLabelName(labelName);
                pl.setOrganizationId(orgId);
                pl.setType(PartnerLabel.REAL_MEMBER);
                labId = partnerLabelService.insert(pl);
            } else {
                PartnerLabel pl = partnerLabelService.get(labId);
                pl.setLabelName(labelName);
                partnerLabelService.update(pl);
            }

            //添加会员
            if (null != addMembers && addMembers.length() != 0) {
                String[] addarrs = addMembers.split(",");
                for (String am : addarrs) {
                    String[] s = am.split("_");
                    String userId = s[0];
                    String partnerId = s[1];
                    PartnerMemberLabel pmbObj = partnerMemberLabelService.getMemberLabel(partnerId, userId);
                    if (null == pmbObj) {
                        PartnerMemberLabel pmlobj = new PartnerMemberLabel();
                        pmlobj.setOrganizationId(partnerId);
                        pmlobj.setLabelId(labId);
                        pmlobj.setMemberId(userId);
                        pmlobj.setIsMember(PartnerLabel.REAL_MEMBER);
                        partnerMemberLabelService.insert(pmlobj);
                    } else {
                        pmbObj.setIsMember(PartnerLabel.REAL_MEMBER);
                        pmbObj.setLabelId(labId);
                        partnerMemberLabelService.update(pmbObj);
                    }
                }
            }

            //删除会员
            if (null != delMembers && delMembers.length() > 0) {
                String[] delarrs = delMembers.split(",");
                for (String am : delarrs) {
                    String[] s = am.split("_");
                    String userId = s[0];
                    String partnerId = s[1];
                    PartnerMemberLabel pmlobj = partnerMemberLabelService.getMemberLabel(partnerId, userId);
                    pmlobj.setLabelId("");
                    partnerMemberLabelService.update(pmlobj);
                }
            }

        } catch (Exception be) {
            logger.error("异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success((Object) labId);
    }

    /**
     * 获取用户列表（实名会员/实名用户）
     *
     * @param page
     * @param request
     * @return 交互数据!
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/list")
    public AjaxResult list(Page page, String keyword, String type, String labId, String partnerId, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (StringUtils.isBlank(type)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数验证不通过");
        }
        Map<String, Object> mmp = new HashMap<>();

        try {
            //设置默认一页50条
            page.setLimit(50);
            //机构用户memeberId
            String orgId = "";
            //子账号数据过滤
            List<String> orgIds = null;

            //主账号查询需过滤主机构
            Integer partnerType = null;

            if (StringUtils.isNotEmpty(partnerId)) {
                orgId = partnerId;
            } else {
                orgIds = memberGroupService.getChildWithMy(currentUser.getId());
            }
            //判断当前登录的账号是否为主账号
            boolean result = memberGroupService.isChild(currentUser.getId());
            if (!result) {
                partnerType = PartnerMember.IS_MAIN_TYPE;
            }

            if (!"user".equalsIgnoreCase(type)) {
                //总人数
                Integer totalNum = partnerLabelService.getRealUserCount(orgId, orgIds,partnerType);
                //会员人数
                Integer memNum = partnerLabelService.getMemberUserCount(orgId, orgIds,partnerType);
                mmp.put("totalNum", totalNum);
                mmp.put("memNum", memNum);
                mmp.put("userNum", totalNum);
            }
            List<PartnerRealUserOutput> pruolist = new ArrayList<>();
            // (total/mem/user) total:全部类型 ， mem：实名会员类型 ， user：实名用户类型，
            if ("total".equalsIgnoreCase(type)) {
                pruolist = partnerLabelService.getRealTotalPagelist(orgId, labId, keyword, orgIds,partnerType, page);
            }
            if ("mem".equalsIgnoreCase(type)) {
                pruolist = partnerLabelService.getRealMemberPagelist(orgId, orgIds,partnerType, page);
            }
            if ("user".equalsIgnoreCase(type)) {
                pruolist = partnerLabelService.getRealUserPagelist(orgId, keyword, orgIds, page);
            }

            mmp.put("members", pruolist);

        } catch (Exception be) {
            logger.error("获取用户列表（实名会员/实名用户）异常", be);
            return AjaxResult.error(500, be.getMessage());
        }
        return AjaxResult.success(mmp, page);
    }
}
